<!-- @format -->

<template>
 <view class="home-add-task uno-p-b-[100px] home-index">
  <wd-form ref="formDom" :model="taskModel" :rules="taskRules">
   <wd-cell-group border>
    <!-- 任务名称 -->
    <wd-input label="标题" label-width="100px" prop="label" v-model="taskModel.label" clearable placeholder="请输入标题" />
    <!-- 增加子任务描述 -->
    <wd-cell vertical required custom-class="my-uno-m-t-0" prop="taskSubList">
     <template #title>
      <view class="uno-flex uno-items-center uno-justify-between">
       <view>任务</view>
       <view class="uno-text-[16px] uno-flex uno-items-center" @click="addTaskInfo2List">
        <wd-icon name="add" color="#1989fa"></wd-icon>
        <view class="uno-text-[12px] uno-m-l-[6px] uno-text-[#999]"> {{ taskModel.taskSubList.length }}/{{ maxTaskCount }} </view>
       </view>
      </view>
     </template>
     <template #default>
      <xlj-task-cell v-for="(item, index) in taskModel.taskSubList" custom-class="add-task-cell" :key="item.id" un-check :source="item" @update="updateSubTask($event, index)"></xlj-task-cell>
     </template>
    </wd-cell>
    <!--  -->
    <wd-cell title="类型" center>
     <view class="uno-flex uno-items-center">
      <wd-button v-for="(item, index) in taskTypeOptions" :key="index" size="small" :plain="!(taskModel.taskType == item.value)" hairline @click="setTaskType(item.value)">{{ item.label }}</wd-button>
     </view>
    </wd-cell>
    <!--  -->
    <wd-cell title="级别" center>
     <view class="uno-flex uno-items-center">
      <wd-button v-for="(item, index) in taskPriorityOptions" :key="index" size="small" :plain="!(taskModel.taskPriority == item.value)" hairline @click="setTaskPriority(item.value)">{{ item.label }}</wd-button>
     </view>
    </wd-cell>
    <!-- 今日任务，每日任务，每周任务，每月任务，定时任务 -->
    <wd-cell title="重复" clickable center @click="showSelectTaskType('taskRepeat')">
     <view class="uno-flex uno-items-center uno-justify-end">
      <view>{{ taskRepeatValue }}</view>
      <wd-icon name="arrow-right" size="22px"></wd-icon>
     </view>
    </wd-cell>
    <wd-cell title="开始时间" center>
     <view class="uno-flex uno-items-center uno-justify-end">
      <view class="uno-bg-[#ddd] uno-rounded-[4px] uno-px-[6px] uno-py-[2px] uno-text-[12px] uno-mr-[8px]" v-show="taskModel.taskRepeat != 2" @click="showTimePicker('startTime', 'date')">
       {{ filterDate(taskModel.startTime, 'date') }}
      </view>
      <view class="uno-bg-[#ddd] uno-rounded-[4px] uno-px-[6px] uno-py-[2px] uno-text-[12px]" @click="showTimePicker('startTime', 'time')">
       {{ filterDate(taskModel.startTime, 'time') }}
      </view>
     </view>
    </wd-cell>
    <wd-cell title="结束时间" center>
     <view class="uno-flex uno-items-center uno-justify-end">
      <view class="uno-bg-[#ddd] uno-rounded-[4px] uno-px-[6px] uno-py-[2px] uno-text-[12px] uno-mr-[8px]" v-show="taskModel.taskRepeat != 2" @click="showTimePicker('endTime', 'date')">
       {{ filterDate(taskModel.endTime, 'date') }}
      </view>
      <view class="uno-bg-[#ddd] uno-rounded-[4px] uno-px-[6px] uno-py-[2px] uno-text-[12px]" @click="showTimePicker('endTime', 'time')">
       {{ filterDate(taskModel.endTime, 'time') }}
      </view>
     </view>
    </wd-cell>
    <!-- 2小时，4小时，8小时，12小时 -->
    <wd-cell title="提醒" clickable label="开始后每2小时提醒一次" @click="showSelectTaskType('taskRemind')">
     <view class="uno-flex uno-items-center uno-justify-end">
      <view>{{ taskRemindValue }}</view>
      <wd-icon name="arrow-right" size="22px"></wd-icon>
     </view>
    </wd-cell>
   </wd-cell-group>
  </wd-form>
  <view class="uno-fixed uno-bottom-0 uno-left-0 uno-w-full uno-flex uno-justify-center uno-items-center uno-bg-white submit-button uno-z-10" :class="{ 'ios-bottom': isIOS }">
   <wd-button type="primary" size="large" @click="submit">提交</wd-button>
  </view>
  <wd-action-sheet v-model="show" title="请选择" :actions="sheetType == 'taskRepeat' ? taskRepeatOptions : taskRemindOptions" @select="updateTaskRepeat" />
  <wd-datetime-picker ref="pickerDom" v-model="pickerValue" :type="pickerType" label="年月日，时分秒" title="日期选择" @confirm="handleConfirm($event, 'datetime')" />
  <wd-picker ref="repeatDom" v-model="repeatValue" :columns="taskModel.taskRepeat == 3 ? weekColumns : monthColumns" label="周期选择" title="日期选择" @confirm="handleConfirm($event, 'picker')" />
 </view>
</template>

<script setup>
 import dayjs from 'dayjs';
 import useGlobalConfig from '../../store/useGlobalConfig';
 import { uuid, CloudFunction } from '@/utils/index';
 import { dictMap, weekColumns as weekColumnsDict, monthColumns as monthColumnsDict, dayColumns } from '../../utils/dict';
 import { ref, computed } from 'vue';
 import { onLoad } from '@dcloudio/uni-app';
 const maxTaskCount = ref(10);
 const taskTypeOptions = dictMap.task_type;
 const taskPriorityOptions = dictMap.task_priority;
 let pickerSelectKey = null;
 const pickerDom = ref(null);
 const sheetType = ref(null);
 const pickerType = ref('date');
 const pickerValue = ref(Date.now());
 const repeatValue = ref(0);
 const repeatDom = ref(null);
 const weekColumns = ref(weekColumnsDict);
 const monthColumns = ref([monthColumnsDict, dayColumns]);
 const taskRepeatOptions = computed(() => {
  return dictMap.task_repeat.map((item) => {
   return {
    name: item.label,
    color: taskModel.value.taskRepeat == item.value ? '#1989fa' : '#666',
    value: item.value,
   };
  });
 });
 const taskRepeatValue = computed(() => {
  return taskRepeatOptions.value.find((item) => {
   return item.value == taskModel.value.taskRepeat;
  }).name;
 });
 const taskRemindOptions = computed(() => {
  return dictMap.task_remind.map((item) => {
   return {
    name: item.label,
    color: taskModel.value.taskRemind == item.value ? '#1989fa' : '#666',
    value: item.value,
   };
  });
 });
 const taskRemindValue = computed(() => {
  return taskRemindOptions.value.find((item) => {
   return item.value == taskModel.value.taskRemind;
  })?.name;
 });
 const formDom = ref(null);
 const GlobalConfigStore = useGlobalConfig();
 console.log('我要打印的值:', GlobalConfigStore.uniSystemInfo);
 const isIOS = computed(() => {
  return GlobalConfigStore.uniSystemInfo.osName == 'ios';
 });

 const startTime = dayjs(Date.now()).add(0.5, 'h').valueOf();
 const taskModel = ref({
  taskType: '1',
  taskPriority: '1',
  taskRepeat: '1',
  startTime: startTime,
  endTime: dayjs(startTime).add(1, 'h').valueOf(),
  taskRemind: '2',
  taskSubList: [],
 });
 //
 const taskRules = ref({
  label: [
   {
    required: true,
    message: '请输入任务标题',
   },
  ],
  taskSubList: [
   {
    required: true,
    validate: (value) => {
     return value.taskSubList.length == 0 ? Promise.reject('请添加任务内容') : Promise.resolve();
    },
   },
  ],
 });
 //
 const show = ref(false);
 //
 onLoad((params) => {
  const { id } = params;
  if (id) {
   uni.setNavigationBarTitle({ title: '修改任务' });
   return CloudFunction('task-action', (taskAction, openId) => {
    return taskAction
     .getTaskDetail({
      id,
      openId,
     })
     .then((v) => {
      const { data = [], code } = v;
      if (data.length > 0) {
       taskModel.value = data[0];
      }
     });
   });
  }
 });
 //
 function showSelectTaskType(type) {
  show.value = true;
  sheetType.value = type;
 }

 function addTaskInfo2List() {
  if (taskModel.value.taskSubList.length >= maxTaskCount.value) {
   return;
  }
  taskModel.value.taskSubList.push({
   id: uuid(),
   value: '',
   status: '0',
   edit: true,
  });
 }

 function delTaskInfo2List(index) {
  taskModel.value.taskSubList.splice(index, 1);
 }

 function setTaskType(value) {
  taskModel.value.taskType = value;
 }

 function setTaskPriority(value) {
  taskModel.value.taskPriority = value;
 }

 function updateTaskRepeat(data) {
  const { item } = data;
  taskModel.value[sheetType.value] = item.value;
 }

 function updateSubTask(item, index) {
  if (item.content.length == 0 || item.delFlag == '1') {
   taskModel.value.taskSubList.splice(index, 1);
  } else {
   taskModel.value.taskSubList[index] = item;
  }
 }

 function showTimePicker(type, picker_ype) {
  pickerType.value = picker_ype;
  pickerValue.value = taskModel.value[type] || Date.now();
  if (picker_ype === 'time') {
   pickerValue.value = dayjs(pickerValue.value).format('HH:mm');
  }
  if (picker_ype == 'date' && taskModel.value.taskRepeat != 1) {
   const columns = taskModel.value.taskRepeat == 3 ? weekColumns.value : monthColumns.value;
   const index = taskModel.value.taskRepeat == 3 ? dayjs(pickerValue.value).day() : dayjs(pickerValue.value).month();
   repeatValue.value = columns[index];
   repeatDom.value.open();
  } else {
   pickerDom.value.open();
  }
  pickerSelectKey = type;
 }
 //
 function handleConfirm(e, type) {
  console.log('我要打印的值:11111', e);
  let { value } = e;
  let oldTime = taskModel.value[pickerSelectKey] || Date.now();
  oldTime = dayjs(oldTime);
  if (type === 'datetime') {
   if (typeof value == 'string' && value.indexOf(':') > -1) {
    const [hours, min] = value.split(':');
    value = oldTime.hour(hours).minute(min).valueOf();
   } else {
    const hours = oldTime.hour();
    const min = oldTime.minute();
    value = dayjs(value).hour(hours).minute(min).valueOf();
   }
  } else if (type == 'picker') {
   // 选择一个默认是周日的时间
   const hour = oldTime.hour();
   const min = oldTime.minute();
   oldTime = dayjs('1995-01-08').hour(hour).minute(min);
   const task_repeat = taskModel.value.taskRepeat;
   if (task_repeat == 3) {
    const day = weekColumns.value.findIndex((item) => item === value);
    value = oldTime.day(day).valueOf();
    // 周
   } else if (task_repeat == 4) {
    // 月
    let [month, date] = value;
    month = parseInt(month);
    date = parseInt(date);
    value = oldTime.month(month).date(date).valueOf();
   }
  }
  taskModel.value[pickerSelectKey] = value;
 }

 function filterDate(time = Date.now(), type, call = (date) => date) {
  const date = call(dayjs(time));
  const { taskRepeat } = taskModel.value;
  if ((taskRepeat == 3 || taskRepeat == 4) && type == 'date') {
   return taskRepeat == 3 ? weekColumns.value[dayjs(time).day()] : date.format('MM月DD日');
  }
  return date.format(type == 'date' ? 'YYYY年MM月DD日' : 'HH:mm');
 }
 //
 function validateFormValue() {
  return new Promise((resolve, reject) => {
   formDom.value
    .validate()
    .then(({ valid, errors }) => {
     valid ? resolve() : reject(errors);
    })
    .catch((error) => {
     reject(errors);
    });
  });
 }
 async function submit() {
  console.log('我要打印的值:', taskModel.value);
  await validateFormValue();
  const { startTime, endTime, taskSubList } = taskModel.value;
  if (taskSubList.length == 0) {
   return uni.showToast({
    title: '请添加任务内容',
    duration: 2000,
   });
  }
  if (startTime > endTime) {
   return uni.showToast({
    title: '时间错误',
    duration: 2000,
   });
  }
  return CloudFunction('task-action', (taskAction, openId) => {
   return taskAction
    .add({
     params: taskModel.value,
     openId,
    })
    .then((v) => {
     uni.showToast({
      title: '操作成功',
      duration: 2000,
     });
     uni.navigateBack();
    });
  });
 }
</script>

<style lang="scss">
 .home-add-task {
  .submit-button {
   border-top: solid 1px #eaeaea;
   padding-top: 16px;
   padding-bottom: 16px;
  }
  .add-stask-cell {
   border-top: none;
  }
 }
</style>
